"""
面试相关的定时任务
"""
from datetime import datetime, timedelta
from django.utils import timezone
from django.core.management.base import BaseCommand
from django.db import transaction
from .models import InterviewApplication, Interview, InterviewResult
import logging

logger = logging.getLogger(__name__)


class InterviewStatusManager:
    """面试状态管理器"""
    
    @staticmethod
    def check_expired_applications():
        """检查过期的面试申请"""
        now = timezone.now()
        
        # 查找已过期的面试申请（已安排但超过预定时间）
        expired_applications = InterviewApplication.objects.filter(
            status='scheduled',
            scheduled_date__lt=now.date()
        )
        
        expired_count = 0
        for application in expired_applications:
            # 检查是否真的过期（考虑时间）
            if application.scheduled_date and application.scheduled_time_end:
                scheduled_datetime = timezone.datetime.combine(
                    application.scheduled_date,
                    application.scheduled_time_end
                )
                scheduled_datetime = timezone.make_aware(scheduled_datetime)
                
                if now > scheduled_datetime:
                    application.status = 'expired'
                    application.save()
                    expired_count += 1
                    
                    logger.info(f"面试申请 {application.id} 已过期")
        
        return expired_count
    
    @staticmethod
    def check_expired_interviews():
        """检查过期的面试记录"""
        now = timezone.now()
        
        # 查找已过期的面试记录（超时2小时未完成）
        expired_interviews = Interview.objects.filter(
            status__in=['scheduled', 'in_progress'],
            scheduled_time__lt=now - timedelta(hours=2)
        )
        
        expired_count = 0
        for interview in expired_interviews:
            interview.status = 'expired'
            interview.save()
            expired_count += 1
            
            # 同时更新关联的申请状态
            if interview.application:
                interview.application.status = 'expired'
                interview.application.save()
            
            logger.info(f"面试记录 {interview.id} 已过期")
        
        return expired_count
    
    @staticmethod
    def auto_start_scheduled_interviews():
        """自动开始已安排的面试"""
        now = timezone.now()
        
        # 查找应该开始的面试（当前时间在开始时间前后15分钟内）
        start_window = timedelta(minutes=15)
        scheduled_interviews = Interview.objects.filter(
            status='scheduled',
            scheduled_time__gte=now - start_window,
            scheduled_time__lte=now + start_window
        )
        
        started_count = 0
        for interview in scheduled_interviews:
            # 可以添加额外的检查逻辑，比如确认面试官在线等
            # 这里简单地将状态改为可以开始
            pass  # 暂时不自动开始，需要手动开始
        
        return started_count
    
    @staticmethod
    def send_interview_reminders():
        """发送面试提醒"""
        now = timezone.now()
        
        # 查找24小时内的面试
        tomorrow = now + timedelta(hours=24)
        upcoming_interviews = Interview.objects.filter(
            status='scheduled',
            scheduled_time__gte=now,
            scheduled_time__lte=tomorrow
        )
        
        reminder_count = 0
        for interview in upcoming_interviews:
            # TODO: 发送邮件或短信提醒
            # 这里可以集成邮件服务或短信服务
            logger.info(f"应该发送面试提醒: {interview.id}")
            reminder_count += 1
        
        return reminder_count
    
    @staticmethod
    def cleanup_old_data():
        """清理旧数据"""
        # 清理6个月前的已完成面试记录
        six_months_ago = timezone.now() - timedelta(days=180)
        
        old_applications = InterviewApplication.objects.filter(
            status__in=['completed', 'expired', 'cancelled'],
            created_at__lt=six_months_ago
        )
        
        old_interviews = Interview.objects.filter(
            status__in=['completed', 'expired', 'cancelled'],
            created_at__lt=six_months_ago
        )
        
        # 注意：这里只是标记，不真正删除，以保留历史记录
        # 可以添加一个 is_archived 字段来标记归档状态
        
        return 0  # 暂时不执行清理
    
    @classmethod
    def run_all_checks(cls):
        """运行所有检查"""
        results = {}
        
        try:
            with transaction.atomic():
                results['expired_applications'] = cls.check_expired_applications()
                results['expired_interviews'] = cls.check_expired_interviews()
                results['started_interviews'] = cls.auto_start_scheduled_interviews()
                results['reminders_sent'] = cls.send_interview_reminders()
                results['cleaned_records'] = cls.cleanup_old_data()
                
                logger.info(f"面试状态检查完成: {results}")
                
        except Exception as e:
            logger.error(f"面试状态检查失败: {str(e)}")
            results['error'] = str(e)
        
        return results


class Command(BaseCommand):
    """Django管理命令：检查面试状态"""
    
    help = '检查和更新面试状态'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--check-type',
            type=str,
            choices=['all', 'expired', 'reminders', 'cleanup'],
            default='all',
            help='指定检查类型'
        )
    
    def handle(self, *args, **options):
        check_type = options['check_type']
        
        self.stdout.write(f'开始执行面试状态检查: {check_type}')
        
        manager = InterviewStatusManager()
        
        if check_type == 'all':
            results = manager.run_all_checks()
        elif check_type == 'expired':
            results = {
                'expired_applications': manager.check_expired_applications(),
                'expired_interviews': manager.check_expired_interviews()
            }
        elif check_type == 'reminders':
            results = {
                'reminders_sent': manager.send_interview_reminders()
            }
        elif check_type == 'cleanup':
            results = {
                'cleaned_records': manager.cleanup_old_data()
            }
        
        self.stdout.write(
            self.style.SUCCESS(f'面试状态检查完成: {results}')
        )


def check_interview_status():
    """供外部调用的函数"""
    manager = InterviewStatusManager()
    return manager.run_all_checks()


# Celery任务（如果使用Celery）
try:
    from celery import shared_task
    
    @shared_task
    def check_interview_status_task():
        """Celery定时任务"""
        return check_interview_status()
    
    @shared_task
    def send_interview_reminders_task():
        """发送面试提醒任务"""
        manager = InterviewStatusManager()
        return manager.send_interview_reminders()
        
except ImportError:
    # 如果没有安装Celery，跳过
    pass


# 简单的定时任务调度器（如果不使用Celery）
class SimpleScheduler:
    """简单的任务调度器"""
    
    @staticmethod
    def should_run_hourly_check():
        """检查是否应该运行每小时检查"""
        now = timezone.now()
        # 每小时的第0分钟运行
        return now.minute == 0
    
    @staticmethod
    def should_run_daily_check():
        """检查是否应该运行每日检查"""
        now = timezone.now()
        # 每天凌晨2点运行
        return now.hour == 2 and now.minute == 0
    
    @classmethod
    def run_scheduled_tasks(cls):
        """运行计划任务"""
        results = {}
        
        if cls.should_run_hourly_check():
            # 每小时检查过期状态
            manager = InterviewStatusManager()
            results['hourly'] = {
                'expired_applications': manager.check_expired_applications(),
                'expired_interviews': manager.check_expired_interviews()
            }
        
        if cls.should_run_daily_check():
            # 每日发送提醒和清理
            manager = InterviewStatusManager()
            results['daily'] = {
                'reminders_sent': manager.send_interview_reminders(),
                'cleaned_records': manager.cleanup_old_data()
            }
        
        return results


# 中间件或信号处理器可以调用这个函数
def periodic_check():
    """周期性检查函数"""
    scheduler = SimpleScheduler()
    return scheduler.run_scheduled_tasks()
